package auth;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import lib_model.Account.Account;
import lib_model.Orther.ReturnObj;

/**
 * Servlet implementation class Register
 */
@WebServlet("/auth/Register")
public class Register extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Register() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String usn = request.getParameter("txtUsn");
		String pw = request.getParameter("txtPw");
		String email = request.getParameter("txtEmail");
		RequestDispatcher dis = request.getRequestDispatcher("../pages/register.jsp");
		if (usn != null && pw != null && email != null) {
			HttpSession s = request.getSession();
			Account acc = new Account();
			acc.username = usn;
			ReturnObj obj = acc.GetInformation();
			if (obj.ObjResult == null) {
				acc.password = pw;
				acc.email = email;
				acc.group_id_ref = 2;
				ReturnObj objReturn = acc.Add();
				if (objReturn.Result == true) {
					s.setAttribute("User", acc);
					dis = request.getRequestDispatcher("../pages/home.jsp");
					System.out.println("ok " + objReturn.Result);
				} else {
					request.setAttribute("Err", "Register fail");
					dis = request.getRequestDispatcher("../pages/register.jsp");
				}
			} else {
				request.setAttribute("Err", "Username is exist");
				dis = request.getRequestDispatcher("../pages/register.jsp");
				System.out.println("Username is exist ");
			}
		}
		dis.forward(request, response);
	}

}
